package com.white.algebra.filter;

import com.white.algebra.domain.UserInfo;
import com.white.algebra.service.UserService;
import com.white.algebra.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class manageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        Object user=req.getSession().getAttribute("user");
        String servletPath= req.getServletPath();
        if(user==null){
            if((servletPath!=null)&&((!"/calculate".equals(servletPath))||(!"/user".equals(servletPath)))){
                resp.sendRedirect(req.getContextPath()+"/powerFailer.jsp");
            }else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }else{
            UserInfo userInfo=(UserInfo)user;
            UserService userService=new UserServiceImpl();
            ArrayList<String> arrayList;
            try {
               arrayList=userService.getAllPermission(userInfo.getId());
                if(arrayList.contains(servletPath)){
                    filterChain.doFilter(servletRequest,servletResponse);
                }else {
                    resp.sendRedirect(req.getContextPath()+"/powerFailer.jsp");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }

    @Override
    public void destroy() {

    }
}
